package schedulo.core.task.provider.parameters;

import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;


public class Parameters {

	public static final String VALUE_DELIMITER = "=";

	public static final String ARG_DELIMITER = ",";

	private Hashtable<String, String> arguments;

	public Parameters(String params) throws ParametersException {
		arguments = new Hashtable<String, String>();
		
		if (params != null) {
			StringTokenizer st = new StringTokenizer(params, ARG_DELIMITER);
			while (st.hasMoreTokens()) {
				String argval = st.nextToken();
				StringTokenizer st2 = new StringTokenizer(argval,
						VALUE_DELIMITER);
				if (st2.countTokens() == 2) {
					String argName = st2.nextToken();
					String argValue = st2.nextToken();

					arguments.put(argName, argValue);
				} else {
					throw new ParametersException(
							"Invalid argument=value format: " + argval);
				}
			}
		}
	}
	
	public String toString() {
		Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator();
		String str = "";
		while(it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			str += entry.getKey() + "=" + entry.getValue() + ",";
		}
		return str;
	}

	public String getArgString(String argName) {
		return getArgString(argName, null);
	}

	public String getArgString(String argName, String defaultValue) {
		String value = arguments.get(argName);
		if (value != null) {
			return value;
		}
		return defaultValue;
	}
	
	public File getArgFile(String argName) throws ParametersException {
		String filename = getArgString(argName);
		if(filename == null) {
			throw new ParametersException("Argument: " + argName + ", has a null value.");
		}
		return new File(filename);
	}

	public int getArgInt(String argName, int defaultValue) {
		String value = getArgString(argName);
		if (value != null) {
			return Integer.parseInt(value);
		}
		return defaultValue;
	}
}
